package com.boboPlanet.filter;

import com.boboPlanet.comm.context.TraceIdContext;
import com.boboPlanet.comm.enums.GatewayConstance;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * @Description: TODO 全局日志追踪链路过滤器  设置全局链路日志tranceId
 * @Author: mis_wu
 * @Date: 2023/6/20
 * @Company planet
 * 过滤器顺序： 0、TraceLogFilter -> 1、RouteControlFilter ->2、JwtCheckFilter ->
 *            3、AuthorizationFilter ->4、CustomGatewayFilterFactory ->10101、GrayLoadBalancerFilter
 * @Order(-1) 排序失效，原因？
 **/
@Component
@Slf4j
public class TraceLogFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String reqPath = request.getURI().getPath();

        ServerHttpRequest req = request.mutate().headers(httpHeaders -> {
            String tid = UUID.randomUUID().toString().replace("-", "");

            MDC.put(GatewayConstance.TRANCE_ID_KEY,tid);

            httpHeaders.set(GatewayConstance.TRANCE_ID_KEY,tid);

            //设置请求头标识,用于判断是否执行下一个过滤器  true:放行   false:校验
            httpHeaders.set(GatewayConstance.ALLOW_FILTER, String.valueOf(false));

            TraceIdContext.setTraceId(tid);
        }).build();

        exchange.mutate().request(req);
        log.info("into gateway traceLog filter,will fill traceId and current path is:{}",reqPath);

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
